
Page({
  data: {
    moments: [],
    showPublishModal: false,
    showConfirmModal: false,
    showCommentInput: false,
    currentCommentIndex: -1,
    commentInputValue: "",
    contentInput: "",
    currentImages: [],
    canPublish: false,
    showToast: false,
    toastMessage: "",
    deletingIndex: -1
  },

  onLoad() {
    this.loadMoments();
  },

  onPullDownRefresh() {
    this.loadMoments();
    wx.stopPullDownRefresh();
  },

  loadMoments() {
    try {
      const moments = wx.getStorageSync('moments') || [];
      this.setData({ moments });
    } catch (error) {
      console.error('加载动态数据失败:', error);
      // 使用模拟数据
      const mockMoments = [
        {
          id: 1,
          userId: "张三",
          content: "今天天气真好，出去散步看到了美丽的夕阳🌇",
          timestamp: Date.now() - 2 * 60 * 60 * 1000,
          images: [
            "https://images.unsplash.com/photo-1502082553048-f009c37129b9?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80"
          ],
          liked: true,
          comments: [
            { author: "李四", content: "真美！这是哪里？" },
            { author: "王五", content: "夕阳无限好～" }
          ]
        },
        {
          id: 2,
          userId: "李四",
          content: "新入手了一本书，推荐给大家《JavaScript高级程序设计》",
          timestamp: Date.now() - 5 * 60 * 60 * 1000,
          images: [
            "https://images.unsplash.com/photo-1544947950-fa07a98d237f?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=80"
          ],
          liked: false,
          comments: [
            { author: "张三", content: "这本书确实不错！" }
          ]
        }
      ];
      this.setData({ moments: mockMoments });
    }
  },

  saveMoments() {
    try {
      wx.setStorageSync('moments', this.data.moments);
    } catch (error) {
      console.error('保存动态数据失败:', error);
      this.showToast('保存失败，请重试');
    }
  },

  openPublishModal() {
    this.setData({
      showPublishModal: true,
      contentInput: "",
      currentImages: [],
      canPublish: false
    });
  },

  closePublishModal() {
    this.setData({ showPublishModal: false });
  },

  onContentInput(e) {
    const contentInput = e.detail.value;
    const canPublish = contentInput.trim() || this.data.currentImages.length > 0;
    this.setData({ contentInput, canPublish });
  },

  addImage() {
    if (this.data.currentImages.length >= 9) {
      this.showToast('最多只能上传9张图片');
      return;
    }

    wx.chooseImage({
      count: 9 - this.data.currentImages.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const currentImages = this.data.currentImages.concat(res.tempFilePaths);
        const canPublish = this.data.contentInput.trim() || currentImages.length > 0;
        this.setData({ currentImages, canPublish });
      }
    });
  },

  removeImageFromCurrent(e) {
    const index = e.currentTarget.dataset.index;
    const currentImages = this.data.currentImages.filter((_, i) => i !== index);
    const canPublish = this.data.contentInput.trim() || currentImages.length > 0;
    this.setData({ currentImages, canPublish });
  },

  publishMoment() {
    const { contentInput, currentImages } = this.data;
    
    if (!contentInput.trim() && currentImages.length === 0) {
      this.showToast('内容或图片不能为空');
      return;
    }

    const newMoment = {
      id: Date.now(),
      userId: "我的名字",
      content: contentInput,
      timestamp: Date.now(),
      images: currentImages,
      liked: false,
      comments: []
    };

    const moments = [newMoment, ...this.data.moments];
    this.setData({ moments });
    this.saveMoments();
    this.closePublishModal();
    this.showToast('发布成功');
  },

  likeMoment(e) {
    const index = e.currentTarget.dataset.index;
    const moments = this.data.moments.map((item, i) => {
      if (i === index) {
        return { ...item, liked: !item.liked };
      }
      return item;
    });
    
    this.setData({ moments });
    this.saveMoments();
  },

  showDeleteConfirm(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ 
      showConfirmModal: true,
      deletingIndex: index
    });
  },

  closeConfirmModal() {
    this.setData({ 
      showConfirmModal: false,
      deletingIndex: -1
    });
  },

  confirmDeleteMoment() {
    const { moments, deletingIndex } = this.data;
    if (deletingIndex >= 0 && deletingIndex < moments.length) {
      moments.splice(deletingIndex, 1);
      this.setData({ moments });
      this.saveMoments();
      this.showToast('删除成功');
    }
    this.closeConfirmModal();
  },

  focusCommentInput(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      showCommentInput: true,
      currentCommentIndex: index,
      commentInputValue: ""
    });
  },

  onCommentInput(e) {
    this.setData({ commentInputValue: e.detail.value });
  },

  submitComment(e) {
    const index = e.currentTarget.dataset.index;
    const { commentInputValue, moments } = this.data;
    
    if (!commentInputValue.trim()) {
      this.showToast('评论内容不能为空');
      return;
    }

    const updatedMoments = moments.map((item, i) => {
      if (i === index) {
        const comments = item.comments || [];
        return {
          ...item,
          comments: [...comments, {
            author: "我的名字",
            content: commentInputValue
          }]
        };
      }
      return item;
    });

    this.setData({ 
      moments: updatedMoments,
      showCommentInput: false,
      currentCommentIndex: -1,
      commentInputValue: ""
    });
    
    this.saveMoments();
    this.showToast('评论成功');
  },

  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    const urls = this.data.moments
      .map(moment => moment.images || [])
      .flat();
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  showToast(message) {
    this.setData({ 
      showToast: true,
      toastMessage: message
    });
    
    setTimeout(() => {
      this.setData({ showToast: false });
    }, 2000);
  },

  formatTime(timestamp) {
    const now = Date.now();
    const diff = now - timestamp;
    
    if (diff < 60000) {
      return '刚刚';
    } else if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`;
    } else if (diff < 604800000) {
      return `${Math.floor(diff / 86400000)}天前`;
    } else {
      return new Date(timestamp).toLocaleDateString();
    }
  },

  stopPropagation() {
    // 阻止事件冒泡
  }
});